package com.zipking.cloud.springbootmybatis.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * 批处理工具类
 */
public class TaskDisposeUtils {

    /**
     * 用于有入参无返参的情况
     *
     * @param taskList   入参是个list
     * @param threadPool 线程池
     * @param consumer   消费型函数式接口
     * @param <T>        入参类型
     */
    public static <T> void inputListNoReturn(List<T> taskList, Executor threadPool, Consumer<? super T> consumer) throws InterruptedException {
        if (CollUtil.isEmpty(taskList) || Objects.isNull(consumer)) {
            return;
        }
        CountDownLatch countDownLatch = new CountDownLatch(taskList.size());
        for (T item : taskList) {
            threadPool.execute(() -> {
                try {
                    consumer.accept(item);
                } finally {
                    countDownLatch.countDown();
                }
            });
        }
        countDownLatch.await();
    }

    /**
     * 用于有入参有返参的情况
     *
     * @param taskList   入参是个list
     * @param threadPool 线程池
     * @param function   有入参有返参的函数式接口
     * @param <T>        入参类型
     * @param <R>        返参类型
     * @return 返参是根据入参list中的每个内容，各自返回一个list，并放在一个大list里
     */
    public static <T, R> List<R> inputListReturnList(List<T> taskList, Executor threadPool, Function<T, R> function) throws InterruptedException {
        if (CollUtil.isEmpty(taskList) || Objects.isNull(function)) {
            return ListUtil.empty();
        }
        CountDownLatch countDownLatch = new CountDownLatch(taskList.size());
        List<R> rList = new CopyOnWriteArrayList<>();
        for (T item : taskList) {
            threadPool.execute(() -> {
                try {
                    R r = function.apply(item);
                    rList.add(r);
                } finally {
                    countDownLatch.countDown();
                }
            });
        }
        countDownLatch.await();
        return rList;
    }

    public static void disposeTask(String task) {
        System.out.println(String.format("【%s发送成功】", task));
    }

    public static List<String> doWork(String input) {
        return ListUtil.of(input + "_one", input + "_two");
    }

    public static void main(String[] args) {
     /*   try {
            // 调用工具类批处理任务，这些优惠卷taskList，放入线程池treadPool，做什么业务disposeTask下发
            TaskDisposeUtils.send(taskList, threadPool, TaskDisposeUtils::disposeTask);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }*/

    }
}
